package com.dh.core.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dh.core.Exception.ExceptionEnum;
import com.dh.core.common.Results;
import com.dh.manager.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Resource
    private JWTUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setCharacterEncoding("UTF-8");
        /**
         * 判断非空，返回重新登录
         */
        if (Objects.isNull(token)) {
            Results results = Results.fail(ExceptionEnum.JwtCheckException);
            System.out.println(JSONObject.toJSONString(results));
            response.getWriter().write(JSONObject.toJSONString(results));
            return false;
        }
        Map<String, Object> stringObjectMap = jwtUtils.checkToken(token);
        /**
         * 判断解析异常，返回重新登录
         */
        if (Objects.isNull(stringObjectMap)) {
            Results results = Results.fail(ExceptionEnum.JwtCheckException);
            System.out.println(JSONObject.toJSONString(results));
            response.getWriter().write(JSONObject.toJSONString(results));
            return false;
        }
        return true;
    }

}
